<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/16
 * Time: 下午2:07
 */

namespace app\macht\controller;


use app\common\controller\ActionLogs;
use app\common\controller\Ekaipiao;
use app\common\controller\Platurl;
use app\common\model\Agent;
use app\common\model\ActionLog;
use app\common\model\DeviceMicro;
use app\common\model\DevicePrint;
use app\common\model\EfapiaoGoods;
use app\common\model\EfapiaoList;
use app\common\model\Merchant;
use app\common\model\MerchantCashier;
use app\common\model\MerchantCate;
use app\common\model\MerchantContent;
use app\common\model\Momerchant;
use app\common\model\ProfitAccount;
use app\common\model\ProfitList;
use app\common\model\WxOpen;
use Ekaipiao\Epiao;
use think\Config;
use think\Queue;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Weixinpay\Wxtk;

class Mach extends MachBase
{
    public function machlist()
    {
//        var_dump(123);
        //搜索条件
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            $map['merchant'] = array('like', '%' . trim($p_data['merchant']) . '%');
        } else {
            $p_data['merchant'] = '';
        }
        $Merchant = new Merchant();
        $mer_id = $this->get_mer_mid();
        $map['id'] = array('in', $mer_id);
        $maa['id'] = array('in', $mer_id);
        $machlist = $Merchant->where($maa)->select();
        $mach = $Merchant->where($map)->paginate(10, false, ['query' => request()->param()]);
        $Mercate = new MerchantCate();
        $map_cate['parent_id'] = 0;
        $map_cate['status'] = 0;
        $level = $Mercate->where($map_cate)->select();
        $this->assign('machlist', $machlist);
        $this->assign('p_data', $p_data);
        $this->assign('level', $level);
        $this->assign('mach', $mach);
        return $this->fetch();
    }

    private function getqrcodes($mid)
    {

        $jg = action('Qrcodes/qrcode', array(request()->param('mid'), "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Index/pay/id/" . $mid . ".html"));
        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
        exit;
    }

    public function getqrcode()
    {

        $jg = action('Qrcodes/qrcode', array(request()->param('mid'), "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Index/pay/id/" . request()->param('mid') . ".html"));
        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
        exit;
    }

    public function getmercode()
    {
        $map['id'] = request()->param('mid');

        $Merchant = new Merchant();
        $merchant = $Merchant->where($map)->value('merchant');
        $jg = action('Qrcodes/mercode', array(request()->param('mid'), 48, "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Index/pay/id/" . request()->param('mid') . ".html", $merchant));
        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
        exit;
    }

    public function get_mer_code()
    {
        $mid = request()->param('mid');
        $url = '/qrcode/' . $mid . '.png';
        return $url;
    }

    public function machinfo()
    {
        $mer_mid = $this->get_mer_mid();
        $request = request();
        $param = $request->get();
        $map['mid'] = array('in', $mer_mid);
        if ($this->get_qx_mid($param['id'])) {
            $ActionLog = new ActionLog();
            $czlog = $ActionLog->where(array('mid' => $param['id']))->select();
            $Merchant = new Merchant();
            $user = $Merchant->where(array('id' => $param['id']))->relation('MerchantContent')->find();
            $wxopen = WxOpen::get($user['wx_open_id']);
            $this->assign('wxopen', $wxopen);
            $MerchantCashier = new MerchantCashier();
            $DeviceMicro = new DeviceMicro();
            $devicelist = $DeviceMicro->where(array('mid' => $param['id']))->paginate('15', false, ['query' => request()->param()]);
            $cashier = $MerchantCashier->where($map)->select();
            $this->assign('devicelist', $devicelist);
            $this->assign('cashier', $cashier);
            $this->assign('user', $user);
            $this->assign('czlog', $czlog);
            return $this->fetch();
        } else {
            $this->error('您没有权限访问该商户');
        }
    }

    public function getmomerchs()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $ali_mer_id = Momerchant::where($map)->value('ali_merid');
            if ($ali_mer_id) {
                $data = array('code' => 0, 'ali_merid' => $ali_mer_id, 'message' => "获取成功");
            } else {
                $data = array('code' => 1, 'message' => "获取失败");
            }
            return json($data);
        }
    }

    public function getmerchs()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $ali_mer_id = Merchant::where($map)->value('ali_merid');
            if ($ali_mer_id) {
                $data = array('code' => 0, 'ali_merid' => $ali_mer_id, 'message' => "获取成功");
            } else {
                $data = array('code' => 1, 'message' => "获取失败");
            }
            return json($data);
        }
    }

    public function addmach()
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $categories = [$arr['leibie'] . ',' . $arr['leibie2']];
            $Merchant = new Merchant();
            $Momerchant = new Momerchant();
            $top_mid = Session::get('login_top_mid');
            $momach = $Momerchant->where('id', $top_mid)->find();
            $data = $arr;
            if (empty($arr['merchant'])) {
                $data['sub_mch_id'] = $momach['sub_mch_id'];
            } else {
                $data['sub_mch_id'] = trim($arr['sub_mch_id']);
            }
            $data['merchant'] = trim($arr['merchant']);
            $data['top_mid'] = $top_mid;
            $data['wx_open_id'] = $momach['wx_open_id'];
            $data['salesman'] = $momach['salesman'];
            $data['agent'] = $momach['agent'];
            $data['tpl_msg_type'] = $momach['tpl_msg_type'];
            //时间
            $data['times'] = $momach['times'];
            $data['start_time'] = $momach['start_time'];
            $data['end_time'] = $momach['end_time'];
            //费率
            $data['wx_service_charge'] = $arr['wx_service_charge'];
            $data['ali_service_charge'] = $arr['ali_service_charge'];
            $data['pos_service_charge'] = $arr['pos_service_charge'];
            if ($arr['img'] !== '') {
                $data['img'] = $arr['img'];
            } else {
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

                $data['img'] = $http_type . $_SERVER['HTTP_HOST'] . '/uploads/mach/default.jpg';
            }
            $data['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);      //类别
            $data['address'] = trim($arr['address']);                   //地址
            $data["MerchantContent"] = array(
                'contacts' => trim($arr['contacts']),
                'tel' => trim($arr['tel']),
                'address' => trim($arr['address']),
            );
            $data['addtime'] = time();
            $add = $Merchant->allowField(true)->together('MerchantContent')->validate('merchant.add')->save($data);
            if ($add == false) {
                $this->error($Merchant->getError(), url('mach/machlist'));
            } else {
                $this->success('创建成功！', url('mach/machlist'));
                $this->getqrcodes($Merchant->id);
            }
        } else {
            $top_mid = Session::get('login_top_mid');
            $Momerchant = new Momerchant();
            $MerchantCate = new MerchantCate();
            $Merchant = new Merchant();
            $Agent = new Agent();
            $xs_number = $Merchant->where('top_mid', $top_mid)->count();
            $momach = $Momerchant->where('id', $top_mid)->find();
            if ($momach['wx_open_id'] == "" && $momach['momach_type'] == 0) {
                $this->error('商户公众号未授权，请先授权公众号', url('wxsystem/wx_authinfo'));
            }
            $ali_app_id = $Agent->where('id', $momach['agent'])->value('ali_app_id');
            $Platurl = new Platurl();
            $agent_url = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
            if ($ali_app_id) {
                $surl = "https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=" . $ali_app_id . "&redirect_uri=" . $agent_url .
                    "/index.php?s=/wxauth/aliauth/merchid/" . $top_mid;
                $jg = action('Qrcodes/sq_qrcode', array($top_mid, $surl));
            } else {
                $surl = "";
                $jg = "";
            }
            $this->assign('surl', $surl);
            $this->assign('qrcode', $jg);
            $this->assign('topmid', $top_mid);
            if ($xs_number !== (int)$momach['mc_number']) {
                $level = $MerchantCate->where(['level' => 1])->select();
                $this->assign('cate', $level);
                $this->assign('momach', $momach);
                return $this->fetch();
            } else {
//                die("<script>alert('抱歉，您已经超过可创建数量。');history.go(-1)</script>");
                $this->error('抱歉，您已经超过可创建数量。', 'mach/machlist');
            }
        }
    }

    public function machxg($id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $categories = [$arr['leibie'] . ',' . $arr['leibie2']];
            $Merchant = new Merchant();
            $data = $arr;
            $data['sub_mch_id'] = trim($arr['sub_mch_id']);
            $data['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);      //类别
            $data['address'] = trim($arr['address']);                   //地址
            $up = $Merchant->allowField(true)->validate('merchant.edit')->save($data, ['id' => $arr['id']]);
            $ActionLogs = new ActionLogs();
            $ActionLogs->writelog("payos", "mach", "/edit", "e:",json_encode($data,JSON_UNESCAPED_UNICODE));
            if ($up == false) {
                echo $Merchant->getError();
                $this->error('修改失败！', url('mach/machlist'));
            } else {
                $data2 = array(
                    'contacts' => trim($arr['contacts']),
                    'tel' => trim($arr['tel']),
                    'address' => trim($arr['address']),
                );
                $MerchantContent = new MerchantContent();
                $MerchantContent->save($data2, ['mid' => $arr['id']]);
                $this->success('修改成功！', url('mach/machlist'));
            }
        } else {
            $param = request()->get();
            $Merchant = new Merchant();
            $Agent = new Agent();
            $MerchantContent = new MerchantContent();
            $user = $Merchant->where(array('id' => $param['id']))->relation('MerchantContent')->find();
            $userinfo = $MerchantContent->where('mid', $param['id'])->find();
            $ali_app_id = $Agent->where('id', $user['agent'])->value('ali_app_id');
//
            $Platurl = new Platurl();
            $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
            if ($ali_app_id) {
                $surl = "https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=" . $ali_app_id . "&redirect_uri=" . $url['platurl'] .
                    "/index.php?s=/wxauth/aliauthmach/merchid/" . $user['id'];
                $jg = action('Qrcodes/sq_qrcode', array($user['id'], $surl));

            } else {
                $surl = "";
                $jg = "";
            }
            $MerchantCate = new MerchantCate();
            $level = $MerchantCate->where(['level' => 1])->select();
            $this->assign('cate', $level);
            $this->assign('surl', $surl);
            $this->assign('qrcode', $jg);
            $this->assign('user', $user);
            $this->assign('userinfo', $userinfo);
            return $this->fetch();
        }
    }

    public function device_micro_view()
    {
        if (request()->isAjax()) {
            $map['mid'] = request()->post('mid');
            $list = DeviceMicro::where($map)->select();
            return json($list);
        }
    }

    public function device_micro_md_pass()
    {
        if (request()->isAjax()) {
            $arr = request()->post();
            $map['id'] = $arr['id'];
            $data['tk_pass'] = MD5($arr['tk_pass']);
            $DeviceMirco = new DeviceMicro();
            $sa = $DeviceMirco->save($data, $map);
            if ($sa) {
                $arrs = array('code' => 0, 'message' => "退款密码修改成功");
            } else {
                $arrs = array('code' => 1, 'message' => "退款密码修改失败");
            }
            return json($arrs);
        }
    }

    public function device_mirco_jb()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $data['device_code'] = null;
            $data['status'] = 0;
            $DeviceMirco = new DeviceMicro();
            $sa = $DeviceMirco->save($data, $map);
            if ($sa) {
                $arr = array('code' => 0, 'message' => "解绑设备成功");
            } else {
                $arr = array('code' => 1, 'message' => "解绑设备失败");
            }
            return json($arr);
        }

    }

    public function del_device_mirco()
    {
        if (request()->isAjax()) {
            $data['mid'] = array('in', $this->get_mer_mid());
            $data['id'] = request()->post('id');
            $del = DeviceMicro::where($data)->delete();
            if ($del) {
                $arr = array('code' => 0, 'message' => "删除成功");
            } else {
                $arr = array('code' => 1, 'message' => "删除失败");
            }
            return json($arr);
        }
    }

    public function add_device_micro()
    {
        if (request()->isAjax()) {
            $data['mid'] = request()->post('mid');
            $data['device_name'] = request()->post('device_name');
            $data['code'] = action('common/pub/generate_code');
            $data['is_tk'] = request()->post('is_tk');
            $data['tk_pass'] = MD5(request()->post('tk_pass'));
            $DeviceMirco = new DeviceMicro();
            $save = $DeviceMirco->save($data);
            if ($save) {
                $arr = array('code' => 0, 'message' => '添加成功');
            } else {
                $arr = array('code' => 1, 'message' => '添加失败');
            }
            return json($arr);
        }
    }

    //
    public function machdata($arr, $res = "", $type)
    {

    }

    //获取门店列表
    public function get_mer_list()
    {
        $Merchant = new Merchant();
        //   $list =
    }

    //
    public function delmach()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            if ($this->get_qx_mid($arr['id'])) {
                $map['id'] = $arr['id'];
                $Merchant = new Merchant();
                $res = $Merchant->where($map)->delete();
                if ($res) {
                    $data = [
                        'code' => '0',
                        'message' => '删除成功！'
                    ];
                } else {
                    $data = [
                        'code' => '9001',
                        'message' => '删除失败！'
                    ];
                }
            } else {
                $data = [
                    'code' => '9999',
                    'message' => '您没有权限处理该商户！'
                ];
            }
            return json($data);
        }
    }

    public function getmachlist()
    {
        if (Request()->isAjax()) {
            $Merchant = new Merchant();
            $map['id'] = array('in', $this->get_mer_mid());
            $list = $Merchant->where($map)->paginate('10');
            return json($list);
        }
    }

    public function getstorelist()
    {
        if (Request()->isAjax()) {
            $Merchant = new Merchant();
            $top_mid = Session::get('login_top_mid');
            $map['top_mid'] = $top_mid;
            $map['poi_id'] = ['neq', ''];
            $list = $Merchant->where($map)->select();
            return json($list);
            if ($list == false) {
                $data['code'] = 9001;
                $data['list'] = 0;
            } else {
                if (empty($list)) {
                    $data['code'] = 9002;
                    $data['list'] = 0;
                } else {
                    $data['code'] = 0;
                    $data['list'] = $list;
                }
            }
            return json($data);
        }
    }

    //添加打印机
    public function addprint()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            if ($this->get_qx_mid($arr['mid'])) {
                $rules = $this->validate($arr, ['username' => 'require', 'ukey' => 'require', 'sn' => 'require']);
                if (true !== $rules) {
                    // 验证失败 输出错误信息
                    dump($rules);
                } else {
                    $sarr = Session::get('user');
                    $DevicePrint = new DevicePrint();
                    $arrs['username'] = $arr['username'];
                    $arrs['ukey'] = $arr['ukey'];
                    $arrs['sbname'] = $arr['sbname'];
                    $arrs['sn'] = $arr['sn'];
                    $arrs['mid'] = $arr['mid'];
                    $arrs['addtime'] = time();
                    $arrs['adduser'] = $sarr['nickname'];
                    $arrs['leixing'] = 'print';
                    $res = $DevicePrint->save($arrs);
                    if ($res) {
                        $data['code'] = '0';
                        $data['message'] = '添加成功！';
                    } else {
                        $data['code'] = '9001';
                        $data['message'] = '添加失败！';
                    }
                }
            } else {
                $data['code'] = '9999';
                $data['message'] = '您没有权限处理该商户！';
            }
            return json($data);
        }
    }

    //打印机列表
    public function listprint()
    {
        if (Request()->isAjax()) {
            $map['mid'] = request()->post('id');
            $DevicePrint = new DevicePrint();
            $printlist = $DevicePrint->where($map)->select();
            if ($printlist) {
                $this->assign('list', $printlist);
                return $this->fetch();
            }
        }
    }

    //删除打印机
    public function delprint()
    {
        if (Request()->isAjax()) {
            $id = request()->post('id');
            $map['id'] = $id;
            $DevicePrint = new DevicePrint();
            $res = $DevicePrint->where($map)->delete();
            if ($res) {
                $data['code'] = '0';
                $data['message'] = '移除成功！';
            } else {
                $data['code'] = '9001';
                $data['message'] = '移除失败！';
            }
            return json($data);
        }
    }

    //获取同步商户信息
    public function get_momcach()
    {
        if (Request()->isAjax()) {
            $Momerchant = new Momerchant();
            $top_mid = Session::get('login_top_mid');
            $info = $Momerchant->where('id', $top_mid)->find();
            if ($info) {
                $data['code'] = 0;
                $data['data'] = $info;
            } else {
                $data['code'] = 9001;
                $data['message'] = '同步获取失败！';

            }
            return json($data);
        }
    }

    /*
    * 二级分类
    *
    *
    */

    public function getsubcate()
    {
        $param = request()->post();
        $MerchantCate = new MerchantCate();
        $name = $MerchantCate->where(['parent_id' => $param['id']])->select();
        if ($name) {
            $rarr['code'] = '0';
            $rarr['data'] = $name;
            $rarr['message'] = 'success';
        } else {
            $rarr['code'] = '0';
            $rarr['data'] = '';
            $rarr['message'] = 'error';
        }
        return json($rarr);
    }

    public function fapiao()
    {

        $Merchant = new Merchant();
        if (request()->isAjax()) {
            $param = request()->param();
            if ($param['type'] == "send") {

                $s = $this->setfpinfo($param['id'], $param);
                if ($s['result_code'] == "SUCCESS") {

                    $data['efp_address'] = $param['efp_address'];
                    $data['efp_company'] = $param['efp_company'];
                    $data['efp_contact'] = $param['efp_contact'];
                    $data['efp_invoice'] = $param['efp_invoice'];
                    $data['efp_isauto'] = isset($param['efp_isauto']) ? $param['efp_isauto'] : "N";
                    $data['efp_receipt'] = isset($param['efp_receipt']) ? $param['efp_receipt'] : "N";
                    $data['efp_kpjh'] = $param['efp_kpjh'];
                    $data['efp_phone'] = $param['efp_phone'];
                    $data['efp_s_pappid'] = $param['efp_s_pappid'];
                    $data['efp_tel'] = $param['efp_tel'];
                    $data['efp_time_out'] = $param['efp_time_out'];
                    $up = $Merchant->save($data, ['id' => $param['id']]);
                    if ($up) {
                        $re_param['result_code'] = "SUCCESS";
                        $re_param['result_msg'] = "设置成功";

                    } else {
                        $re_param['result_code'] = "FAIL";
                        $re_param['result_msg'] = "设置失败";
                    }
                } else {
                    $re_param = $s;
                }
            } elseif ($param['type'] == "getgoodsinfo") {
                $EfapiaoGoods = new EfapiaoGoods();
                $goodsinfo = $EfapiaoGoods->where('id', $param['id'])->find();
                $re_param['result_code'] = "SUCCESS";
                $re_param['result_msg'] = "获取成功";
                $re_param['goodsinfo'] = $goodsinfo;
            } elseif ($param['type'] == "goods") {
                $data['spmc'] = $param['spmc'];
                $data['spbm'] = $param['spbm'];
                $data['ggxh'] = $param['ggxh'];
                $data['slv'] = $param['slv'];
                $data['jldw'] = $param['jldw'];
                $data['spsl'] = $param['spsl'];
                $data['is_default'] = isset($param['is_default']) ? $param['is_default'] : "N";
                $data['hsbz'] = $param['hsbz'];
                $EfapiaoGoods = new EfapiaoGoods();
                if (!empty($param['goods_id'])) {
                    $up = $EfapiaoGoods->save($data, ['id' => $param['goods_id']]);


                } else {
                    $data['mid'] = $param['mid'];
                    $up = $EfapiaoGoods->save($data);
                }
                if ($up) {
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = "处理成功";
                } else {
                    $re_param['result_code'] = "FAIL";
                    $re_param['result_msg'] = "处理失败";
                }

            } elseif ($param['type'] == "delgoods") {
                $EfapiaoGoods = new EfapiaoGoods();
                $del = $EfapiaoGoods->where('id', $param['id'])->delete();
                if ($del) {
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = "删除成功";
                } else {
                    $re_param['result_code'] = "FAIL";
                    $re_param['result_msg'] = "删除失败";
                }
            } elseif ($param['type'] == "getkaipiaolist") {
                $EfapiaoList = new EfapiaoList();
                $list = $EfapiaoList->where(['mid' => $param['mid']])
                    ->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])->order('status asc')->select();
                $re_param["total"] = count($list);
                //获取的记录
                $re_param["rows"] = $list;
//                return json($re_param);
            } elseif ($param['type'] == "getfpgoodsinfo") {
                $EfapiaoList = new EfapiaoList();
                $list = $EfapiaoList->where(['id' => $param['id']])->value('goodsinfo');
                $list = json_decode($list, true);
                $i = 0;
                foreach ($list as $k => $v) {

                    $lists[$i]['SYYHZCBZ'] = isset($list[$k]['SYYHZCBZ']) ? $list[$k]['SYYHZCBZ'] : "";
                    $lists[$i]['YHZCSM'] = isset($list[$k]['YHZCSM']) ? $list[$k]['YHZCSM'] : "";
                    $lists[$i]['ggxh'] = isset($list[$k]['ggxh']) ? $list[$k]['ggxh'] : "";
                    $hsbz = isset($list[$k]['hsbz']) ? $list[$k]['hsbz'] : "0";
                    $lists[$i]['hsbz'] = (isset($list[$k]['hsbz']) ? $list[$k]['hsbz'] : "0") == "0" ? "不含税" : "含税";
                    $lists[$i]['je'] = isset($list[$k]['je']) ? $list[$k]['je'] : "";
                    $lists[$i]['jldw'] = isset($list[$k]['jldw']) ? $list[$k]['jldw'] : "";
                    $lists[$i]['se'] = isset($list[$k]['se']) ? $list[$k]['se'] : "";
                    $lists[$i]['slv'] = isset($list[$k]['slv']) ? $list[$k]['slv'] : "";
                    $lists[$i]['spdj'] = isset($list[$k]['spdj']) ? $list[$k]['spdj'] : "";
                    $lists[$i]['spmc'] = isset($list[$k]['spmc']) ? $list[$k]['spmc'] : "";
                    $lists[$i]['spsl'] = isset($list[$k]['spsl']) ? $list[$k]['spsl'] : "";
                    $lists[$i]['spbm'] = isset($list[$k]['spbm']) ? $list[$k]['spbm'] : "";
                    $i++;
                }
                $re_param = $lists;
//                return json($re_param);
            } elseif ($param['type'] == "mtfapiao") {
                $mapmt['id'] = $param['id'];
                $EfapiaoList = new EfapiaoList();
                $Ekaipiao = new Ekaipiao();
                $orderid = $EfapiaoList->where($mapmt)->value('orderid');
                $lists = $Ekaipiao->send_kp($orderid);
                $re_param = $lists;
            }
            return json($re_param);

        } else {
//            if (request()->param('id') == "501") {
            $map['id'] = request()->param('id');
            $machinfo = $Merchant->where($map)->find();
            $EfapiaoGoods = new EfapiaoGoods();
            $goodslist = $EfapiaoGoods->where('mid', request()->param('id'))->select();
            $this->assign('goodslist', $goodslist);
            $this->assign('machinfo', $machinfo);
            return $this->fetch();
//            }
        }
    }

    private function setfpinfo($mid, $param)
    {
        $map['id'] = $mid;
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $user['agent']))->find();
        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $usersopen = $WxOpen->where(array('id' => $user['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $usersopen['authorizer_appid'],
            'authorizer_refresh_token' => $usersopen['authorizer_refresh_token'],
            // 'partnerkey'=>$agent['partnerkey']
        );
        $weObj = new Wxobjopen($options);

        $set1_data['contact'] = array(
            "time_out" => $param['efp_time_out'],
            "phone" => $param['efp_phone'],

        );
        $setup1 = $weObj->setcontactinfo($set1_data);
        if ($setup1['errcode'] == 0) {
            $setup2_data['paymch_info'] = array(
                'mchid' => $user['sub_mch_id'],
                's_pappid' => $param['efp_s_pappid'],

            );
            $setup2 = $weObj->setpaymch($setup2_data);
//            return $setup2_data;

            if ($setup2['errcode'] == 0) {
                $setup3 = $this->efapiaoset($mid);
                if ($setup3['result_code'] == "SUCCESS") {
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = "SUCCESS";
                } else {
                    $re_param = $setup3;
                }
            } else {
                $re_param['result_code'] = "FAIL";
                $re_param['result_msg'] = $setup2['errmsg'];
            }

        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = $setup1['errmsg'];
        }
        return $re_param;
    }

    private function efapiaoset($mid)
    {
        $Merchant = new Merchant();
        $machinfo = $Merchant->where('id', $mid)->find();
        if ($machinfo['efp_token'] == "") {
            $Epiao = new Epiao();
            $data = array(
                "company" => $machinfo['efp_company'],
                "invoice" => $machinfo['efp_invoice'],
                "kpjh" => $machinfo['efp_kpjh'],
                "address" => $machinfo['efp_address'],
                "tel" => $machinfo['efp_tel'],
                "contact" => $machinfo['efp_contact'],
            );
            $at = $Epiao->register($data);
            if ($at && $at['errcode'] == "200") {
                $token = $at['info'][0]['token'];
                $Merchant->save(['efp_token' => $token, 'efp_time' => time()], ['id' => $mid]);
                $re_param['result_code'] = "SUCCESS";
                $re_param['result_msg'] = "设置成功";
            } else {
                $re_param['result_code'] = "SUCCESS";
                $re_param['result_msg'] = "开票平台注册失败";
            }

        } else {
            $re_param['result_code'] = "SUCCESS";
            $re_param['result_msg'] = "设置成功";
        }

        return $re_param;
    }

    public function profit(Request $request)
    {
        if ($request->isAjax()) {
            $param = $request->post();
            if ($param['type'] == "setup") {
                $data['is_profit'] = isset($param['is_profit']) ? $param['is_profit'] : "N";
                $data['profit_time'] = $param['profit_time'];
                $Merchat = new Merchant();
                $up = $Merchat->save($data, ['id' => $param['id']]);
                if ($up) {
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = "设置成功";

                } else {
                    $re_param['result_code'] = "FAIL";
                    $re_param['result_msg'] = "设置失败";
                }

            } elseif ($param['type'] == "addaccount") {
                $setprofitaccount = $this->setprofitaccount($param);
                if ($setprofitaccount['result_code'] == "SUCCESS") {
                    $ProfitAccount = new ProfitAccount();
                    $data['type'] = $param['profit_type'];
                    $data['mid'] = $param['mid'];
                    $data['account'] = $param['account'];
                    $data['name'] = $param['name'];
                    $data['fz_type'] = $param['fz_type'];
                    $data['fz_num'] = $param['fz_num'];
//                    $data['channel'] = $param['channel'];
                    $up = $ProfitAccount->save($data);
                    if ($up) {
                        $re_param['result_code'] = "SUCCESS";
                        $re_param['result_msg'] = "设置成功";
                    } else {
                        $re_param['result_code'] = "FAIL";
                        $re_param['result_msg'] = "设置失败";
                    }
                } else {
                    $re_param = $setprofitaccount;
                }
            } elseif ($param['type'] == "delaccount") {
                $delprofitaccount = $this->delprofitaccount($param);
                if ($delprofitaccount['result_code'] == "SUCCESS") {
                    $ProfitAccount = new ProfitAccount();
                    $del = $ProfitAccount->where('id', $param['fz_id'])->delete();
                    if ($del) {
                        $re_param['result_code'] = "SUCCESS";
                        $re_param['result_msg'] = "删除成功";
                    } else {
                        $re_param['result_code'] = "FAIL";
                        $re_param['result_msg'] = "删除失败";
                    }
                } else {
                    $re_param = $delprofitaccount;
                }
            } elseif ($param['type'] == "getprofitlist") {
                $ProfitList = new ProfitList();
                $list = $ProfitList->where(['mid' => $param['mid']])
                    ->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])->order('id desc')->select();
                foreach ($list as $k => $v) {
                    if (!empty($v['work_time'])) {
                        $work_time = date('Y-m-d H:i:s', $v['work_time']);
                    } else {
                        $work_time = "";
                    }
                    $list[$k]['work_time'] = $work_time;
                    $list[$k]['work_status'] = getprofit_status($v['status']);
                }
                $re_param["total"] = count($list);
                //获取的记录
                $re_param["rows"] = $list;
            }elseif ($param['type'] == "mtfenzhang") {
                $mapmt['id'] = $param['id'];
                $ProfitList = new ProfitList();
                $info=$ProfitList->where($mapmt)->find();
                if ($info['status'] == 'P') {
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = "请等待分账完成";
                }elseif($info['status'] == 'Y') {
                    $re_param['result_code'] = "ERROR";
                    $re_param['result_msg'] = "请勿重复操作";
                }else{
                    $datap['status'] = 'P';
                    $ProfitList->save($datap, $mapmt);
                    $this->task_biz_fenzhang($info);
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = "处理成功";
                }
            }
            return json($re_param);
        } else {

                $map['id'] = $request->param('id');
                $Merchat = new Merchant();
                $machinfo = $Merchat->where($map)->find();
                $ProfitAccount = new ProfitAccount();
                $userlist = $ProfitAccount->where(['mid' => $request->param('id')])->select();
                $this->assign('userlist', $userlist);
                $this->assign('machinfo', $machinfo);
                return $this->fetch();

        }
    }
    private function task_biz_fenzhang($data = ''){

        // 1.当前任务将由哪个类来负责处理。
        //   当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
        $jobHandlerClassName  = 'app\merchant\job\Fenzhang';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName  	  = "task_biz_fenzhang";
        // 3.当前任务所需的业务数据 . 不能为 resource 类型，其他类型最终将转化为json形式的字符串
        //   ( jobData 为对象时，需要在先在此处手动序列化，否则只存储其public属性的键值对)
        $jobData = $data ;
        // 4.将该任务推送到消息队列，等待对应的消费者去执行
        $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName );
        // database 驱动时，返回值为 1|false  ;   redis 驱动时，返回值为 随机字符串|false
        if( $isPushed !== false ){
            return 'success';
        }else{
            return 'error';
        }
    }
    private function setprofitaccount($param)
    {
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $param['mid'];
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);

        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $nonce_str = $weObj->generateNonceStr();
        $receiver = array(
            'type' => $param['profit_type'],
            'account' => $param['account'],
            'name' => $param['name'],
        );

        $options['wx_open_id'] = $agent['wx_open_id'];
        $weObj = new Wxtk($options);
        $weObj->setParameter('appid', $appid);
        $weObj->setParameter('sub_appid', $sub_appid);
        $weObj->setParameter('mch_id', $mch_id);
        $weObj->setParameter('sub_mch_id', $sub_mch_id);
        $weObj->setParameter('nonce_str', $nonce_str);
        $weObj->setParameter('receiver', json_encode($receiver, JSON_UNESCAPED_UNICODE));
        $sss = $weObj->create_fz_xml($agent['partnerkey']);

//        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharing';//分账
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharingaddreceiver';//添加分账人
//        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharingremovereceiver';//删除分账人
        $responseXml = $weObj->curl_post_ssl($url, $sss);

        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $responseArr = ( array )$responseObj;
        if ($responseArr['return_code'] == "SUCCESS") {
            if ($responseArr['result_code'] == "SUCCESS") {
                $re_param['result_code'] = "SUCCESS";
                $re_param['result_msg'] = "成功";
            } else {
                $re_param['result_code'] = "FAIL";
                $re_param['result_msg'] = $responseArr['err_code'] . $responseArr['err_code_des'];
            }
        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = $responseArr;
        }
        return $re_param;
    }

    private function delprofitaccount($param)
    {
        $ProfitAccount = new ProfitAccount();
        $fzinfo = $ProfitAccount->where(['id' => $param['fz_id']])->find();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $fzinfo['mid'];

        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $userwx = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'appid' => $users['authorizer_appid'], // 填写高级调用功能的app id
            'partnerid' => $agent['partnerid'], // 财付通商户身份标识
            'partnerkey' => $agent['partnerkey'], // 财付通商户权限密钥Key
        );
        $weObj = new Wxobjopen($options);

        $appid = $users['authorizer_appid'];
        $mch_id = $agent['partnerid'];
        $sub_mch_id = $config['sub_mch_id'];
        $sub_appid = $userwx['authorizer_appid'];
        $nonce_str = $weObj->generateNonceStr();
        $receiver = array(
            'type' => $fzinfo['type'],
            'account' => $fzinfo['account'],
        );

        $options['wx_open_id'] = $agent['wx_open_id'];
        $weObj = new Wxtk($options);
        $weObj->setParameter('appid', $appid);
        $weObj->setParameter('sub_appid', $sub_appid);
        $weObj->setParameter('mch_id', $mch_id);
        $weObj->setParameter('sub_mch_id', $sub_mch_id);
        $weObj->setParameter('nonce_str', $nonce_str);
        $weObj->setParameter('receiver', json_encode($receiver, JSON_UNESCAPED_UNICODE));
        $sss = $weObj->create_fz_xml($agent['partnerkey']);

//        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharing';//分账
//        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharingaddreceiver';//添加分账人
        $url = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharingremovereceiver';//删除分账人
        $responseXml = $weObj->curl_post_ssl($url, $sss);

        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $responseArr = ( array )$responseObj;
        if ($responseArr['return_code'] == "SUCCESS") {
            if ($responseArr['result_code'] == "SUCCESS") {
                $re_param['result_code'] = "SUCCESS";
                $re_param['result_msg'] = "成功";
            } else {
                $re_param['result_code'] = "FAIL";
                $re_param['result_msg'] = $responseArr['err_code'] . $responseArr['err_code_des'];
            }
        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = $responseArr;
        }
        return $re_param;
    }
//    public function open_auth()
//    {
//        $request = request();
//        $System = new \app\common\model\System();
//        $config = $System->where(array('id' => 1))->find();
//        $options = array(
//            'component_token' => $config['component_token'], // 填写你设定的key
//            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
//            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
//            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
//            'open_ticket' => $config['open_ticket'],
//        );;
//        $weObj = new Wxobjopen($options);
//        $pre_auth_code = $weObj->get_pre_auth_code();
//        if (!$request->get('auth_code')) {
//            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
//            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("mach/open_auth", $_GET);
//            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
//            header("Location: $url");
//            exit();
//        } else {
//            $appinfo = $weObj->authorization_info($request->get('auth_code'));
//            $auth_appid = $appinfo['authorization_info']['authorizer_appid'];
//            $auther['component_appid'] = $config['component_appid'];
//            $auther['authorizer_appid'] = $auth_appid;
//            $auther_info = $weObj->get_auther_info($auther);
//            if ($auther_info['authorizer_info']['service_type_info']['id'] == 2 && ($auther_info['authorizer_info']['verify_type_info']['id'] == 0 || $auther_info['authorizer_info']['verify_type_info']['id'] == 3)) {
//                $data['gh_nick_name'] = $auther_info['authorizer_info']['nick_name'];
//                $data['service_type_info'] = $auther_info['authorizer_info']['service_type_info']['id'];
//                $data['verify_type_info'] = $auther_info['authorizer_info']['verify_type_info']['id'];
//                $data['gh_id'] = $auther_info['authorizer_info']['user_name'];
//                $data['alias'] = $auther_info['authorizer_info']['alias'];
//                $data['qrcode_url'] = $auther_info['authorizer_info']['qrcode_url'];
//                $data['principal_name'] = $auther_info['authorizer_info']['principal_name'];
//                $data['wx_open_info'] = json_encode($auther_info, JSON_UNESCAPED_UNICODE);
//                $data['authorizer_appid'] = $auth_appid;
//                $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
//                $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
//                $data['at_addtime'] = time();
//                $data['at_expires_in'] = 7000;
//                $data['addtime'] = time();
//                $data['zt'] = 1;
//                $func_info = "";
//                foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
//                    $func_info .= $v['funcscope_category']['id'] . ',';
//                }
//                $WxOpen = new WxOpen();
//                $data['func_info'] = $func_info;
//                $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();
//                if ($wx_open) {
//                    $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
//                    $da2['wx_open_id'] = $wx_open['id'];
//                } else {
//                    $sj = $WxOpen->save($data);
//                    $da2['wx_open_id'] = $WxOpen->id;
//                }
//                $da2['auth_type'] = 1;
//                $mss['id'] = request()->param('id');
//                $Merchant = new Merchant();
//                $Merchant->save($da2, $mss);
//                if ($sj) {
//                    $this->success('授权成功', url("mach/machinfo")."?id=". request()->param('id'));
//                } else {
//                    $this->error('授权失败');
//                }
//            } else {
//                $this->error('该公众号为订阅号或者未通过微信认证，请确认后重新授权');
//            }
//        }
//    }
}